package eproject.mm.com.projectsupervision.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.suke.widget.SwitchButton;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import eproject.mm.com.projectsupervision.BuildConfig;
import eproject.mm.com.projectsupervision.PrjApplication;
import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.adapter.PassengerAdapter;
import eproject.mm.com.projectsupervision.adapter.ProjectSelectAdapter;
//import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import eproject.mm.com.projectsupervision.util.PhotoLayoutManage;
import eproject.mm.com.projectsupervision.widget.IconFontTextview;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ReportActivity extends Activity{
    private static final String TAG = ReportActivity.class.getName();

    private static final int RequestCode_ProjectSelect = 10005;
    private static final int RequestCode_PlanNodeSelect = 10006;

    public static final String TYPE = "application/octet-stream";

    ImageView iv_takePhoto;
    RecyclerView rv_photos;
    PassengerAdapter passengerAdapter;
    ArrayList imageUrls;
    int poss;


    //==========
    String sPrjId = "";
    TextView tv_PrjName;
    String sPlanNodeId = "";
    TextView tv_PlanNode;
    EditText et_intro;
    EditText et_rate;
    //==========
    String imageFilePath,imageFileName;

    private OkHttpClient client;
    IconFontTextview iftv_back;
    SwitchButton sb_noWork;
    RelativeLayout rl_planNode, rl_prjSchedule;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report);

        initView();
        initEvent();

        iftv_back = (IconFontTextview)findViewById(R.id.iftv_back);
        iftv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        loadData();

        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    private void initView(){
        //iv_takePhoto = (ImageView)findViewById(R.id.iv_takePhoto);
        rv_photos = (RecyclerView)findViewById(R.id.rv_photos);
        tv_PrjName = (TextView)findViewById(R.id.tv_prjName);
        tv_PlanNode = (TextView)findViewById(R.id.tv_PlanNode);
        et_intro = (EditText) findViewById(R.id.et_intro);

        et_intro.setHintTextColor(Color.GRAY);
        et_rate = (EditText) findViewById(R.id.et_rate);
        sb_noWork = (SwitchButton)findViewById(R.id.sb_noWork);
        rl_planNode = (RelativeLayout)findViewById(R.id.rl_planNode);
        rl_prjSchedule = (RelativeLayout)findViewById(R.id.rl_prjSchedule);
    }
    private void initEvent(){
        sb_noWork.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton buttonView, boolean isChecked) {
                if(isChecked){
                    rl_planNode.setVisibility(View.GONE);
                    rl_prjSchedule.setVisibility(View.GONE);
                    if(et_intro.getText().toString().equals("")) {
                        et_intro.setText("未施工");
                    }
                }else{
                    rl_planNode.setVisibility(View.VISIBLE);
                    rl_prjSchedule.setVisibility(View.VISIBLE);
                    if(et_intro.getText().toString().equals("未施工")) {
                        et_intro.setText("");
                    }
                }
            }
        });
    }

    private void loadData(){
        imageUrls = new ArrayList();
        imageUrls.add("hehe");

        passengerAdapter = new PassengerAdapter(this, imageUrls);
        //rv_photos.setLayoutManager(new PhotoLayoutManage(this, 4, passengerAdapter));

        rv_photos.setLayoutManager(new GridLayoutManager(this, 4) {
            @Override
            public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
                super.onMeasure(recycler, state, widthSpec, heightSpec);
//              int measuredWidth = rv_photos.getMeasuredWidth();
//              int measuredHeight = rv_photos.getMeasuredHeight();
//              int myMeasureHeight = 0;
//              int count = state.getItemCount();
//              for (int i = 0; i < count; i++) {
//                  View view = recycler.getViewForPosition(i);
//                  if (view != null) {
//                      if (myMeasureHeight < measuredHeight && i % 4 == 0) {
//                          RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
//                          int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
//                                  getPaddingLeft() + getPaddingRight(), p.width);
//                          int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
//                                  getPaddingTop() + getPaddingBottom(), p.height);
//                          view.measure(childWidthSpec, childHeightSpec);
//                          myMeasureHeight += view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
//                      }
//                      recycler.recycleView(view);
//                  }
//              }
//              setMeasuredDimension(measuredWidth, Math.min(measuredHeight, myMeasureHeight));
            }
        });
        rv_photos.getLayoutManager().setAutoMeasureEnabled(true);
        rv_photos.setAdapter(passengerAdapter);

        passengerAdapter.setOnItemClickLitener(new PassengerAdapter.OnItemClickLitener() {
            @Override
            public void onBigClick(int position) {
                if (position==imageUrls.size()-1) {

                    String name = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date());

                    //File outputImage = new File(getExternalCacheDir(),name+".jpg");
                    File outputImage = new File(Environment.getExternalStorageDirectory(),name+".jpg");
                    imageFilePath = outputImage.getPath();

                    android.net.Uri imageUri;
                    if(outputImage.exists())
                    {
                        outputImage.delete();
                        try
                        {
                            outputImage.createNewFile();
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    }
                    imageFileName = outputImage.getName();
                    if (Build.VERSION.SDK_INT>=24)
                    {
                        //imageUri = FileProvider.getUriForFile(ReportActivity.this,"eproject.mm.com.projectsupervision.fileProvider",outputImage);
                        imageUri = FileProvider.getUriForFile(ReportActivity.this, BuildConfig.APPLICATION_ID+".provider",outputImage);

                    }else{
                        imageUri = Uri.fromFile(outputImage);
                        imageFilePath = imageUri.getPath();
                    }

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                        if ((ContextCompat.checkSelfPermission(ReportActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)||
                                (ContextCompat.checkSelfPermission(ReportActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                            //如果没有授权，则请求授权
                            ActivityCompat.requestPermissions(ReportActivity.this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                        } else {
                            //有授权，直接开启摄像头
                            //6.0 camera

                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (intent.resolveActivity(getPackageManager())!=null){
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                                startActivityForResult(intent, 1);
                            }
                        }

//                        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                        takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                        takePictureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//                        takePictureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//                        startActivityForResult(takePictureIntent,1);
                    }else{
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        startActivityForResult(intent,1);
                    }

//                    //添加本地相册图片，更新视图
//                    Intent intent = new Intent(ReportActivity.this, MultiImageSelectorActivity.class);
//                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
//                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
//                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
//                    startActivityForResult(intent, 10001);//10001-->添加
                } else {
//                    Intent intent = new Intent(ReportActivity.this, MultiImageSelectorActivity.class);
//                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
//                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
//                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
//                    //poss = position;
//                    startActivityForResult(intent, 10002);//10002-->修改
                    //修改图片，更新视图
                }

            }
            @Override
            public void onSmallClick(int position) {
                imageUrls.remove(position);
                passengerAdapter.notifyItemRemoved(position);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //if(data!=null){
            if(requestCode == RequestCode_ProjectSelect && data != null){
                Bundle bundle = data.getExtras();
                String id = bundle.getString("id");
                String name = bundle.getString("name");

                sPrjId = id;
                tv_PrjName.setText(name);
            }else if(requestCode == RequestCode_PlanNodeSelect && data != null){
                Bundle bundle = data.getExtras();
                String id = bundle.getString("id");
                String name = bundle.getString("name");

                sPlanNodeId = id;
                tv_PlanNode.setText(name);
            }else if(requestCode == 1){
                if(resultCode == RESULT_OK){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imageUrls.add(0,imageFilePath);
                            //更新第一个位置的图片
                            passengerAdapter.notifyItemInserted(0);
                        }
                    });
                }
            }
        //}

    }

    public void onSubmit(View view){
        if(sPrjId.equals("")){
            Toast.makeText(this,"请选择项目",Toast.LENGTH_SHORT).show();
            return;
        }
        if(sPlanNodeId.equals("") && !sb_noWork.isChecked()){
            Toast.makeText(this,"请选择计划节点",Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_intro.getText().toString().trim().equals("")){
            Toast.makeText(this,"请输入进度描述",Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_rate.getText().toString().trim().equals("") && !sb_noWork.isChecked()){
            Toast.makeText(this,"请输入项目进度",Toast.LENGTH_SHORT).show();
            return;
        }

        final LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("加载中...")//设置loading时显示的文字
                .show();

        MultipartBody.Builder builder = new MultipartBody.Builder();

        for(int i=0; i < imageUrls.size()-1; i++) {
            String filePath = (String)imageUrls.get(i);
            File imageFile = new File(filePath);
            RequestBody fileBody = RequestBody.create(MediaType.parse(TYPE), imageFile);
            builder.addFormDataPart("files", imageFile.getName(), fileBody);
        }
        if(sb_noWork.isChecked()){
            sPlanNodeId = "";
            et_rate.setText("");
        }
        builder.addFormDataPart("project",sPrjId);
        builder.addFormDataPart("task",sPlanNodeId);
        builder.addFormDataPart("percentdone",et_rate.getText().toString());
        builder.addFormDataPart("describes",et_intro.getText().toString());

        RequestBody requestBody = builder.build();

        Request.Builder okbuilder = new Request.Builder();
        okbuilder.addHeader("authenticationToken",PrjApplication.getInstance().getAuthenticationToken());
        Request requestPostFile = okbuilder
                .url("http://"+ PrjApplication.getInstance().getServerIp() +":"+PrjApplication.getInstance().getServerPort()+"/"+PrjApplication.getInstance().getPreFixPath()+"/planSubmit")
                .post(requestBody)
                .build();
        client.newCall(requestPostFile).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                loadingDialog.close();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.close();
                        ReportActivity.this.finish();
                    }
                });
            }
        });
    }
    public void back(View view) {
        finish();
    }

    public void onPlanNodeClick(View view){
        if(sPrjId.equals("")){
            Toast.makeText(this, "请先选择项目", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(ReportActivity.this, PlanNodeActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("prjID",sPrjId);
        intent.putExtras(bundle);

        //poss = position;
        startActivityForResult(intent, RequestCode_PlanNodeSelect);//10002-->修改
    }

    public  void onProjectSelectClick(View view){
        Intent intent = new Intent(ReportActivity.this, ProjectSelectActivity.class);
        //poss = position;
        startActivityForResult(intent, RequestCode_ProjectSelect);
    }
}
